﻿
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using MyApp.Repository;
using Net6Shell.Dto;
using Net6Shell.IRepository;
using SqlSugar;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Net6Shell.Extensions
{
    public static class IocServiceSetup
    {
        
        /// <summary>
        /// NetCore自带容器中注入
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static void AddIocSetup(this IServiceCollection services)
        {
            #region 单个注入
            //services.AddScoped<IInterfaceToolRepository, InterfaceToolRepository>();
            //services.AddScoped<IInterfaceToolService, InterfaceToolService>(); 
            #endregion

            
            //查找dll 注入
            //var path = AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory;
            //var referencedAssemblies = System.IO.Directory.GetFiles(path, "*Shell.dll").Where(c => c.Contains("Repository") || c.Contains("Service")).Select(Assembly.LoadFrom).ToArray();
            //当前dll
            //Assembly.GetExecutingAssembly()
            var referencedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
            var types = referencedAssemblies
                .SelectMany(a => a.DefinedTypes)
                .Select(type => type.AsType())
                .Where(t => t.Name.EndsWith("Repository")).ToArray();
            var implementTypes = types.Where(x => x.IsClass).ToArray();
            var interfaceTypes = types.Where(x => x.IsInterface).ToArray();
            foreach (var implementType in implementTypes)
            {
                var interfaceType = interfaceTypes.FirstOrDefault(x => x.IsAssignableFrom(implementType));
                if (interfaceType != null)
                    services.AddScoped(interfaceType, implementType);
            }

           
        }
    }
}
